<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 提示框 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- 进度框 -->
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- tag导航 -->
      <el-form
        :model="goodsinfo"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-position="top"
      >
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          tab-position="left"
          :before-leave="beforeTagLeave"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsinfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="goodsinfo.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsinfo.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsinfo.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联菜单 -->
              <el-cascader
                v-model="goodsinfo.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in checkList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  size="small"
                  :label="item1"
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, i) in onlyData"
              :key="i"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handSuccess"
              list-type="picture"
              :headers="tokenHeader"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <el-dialog
              title="提示"
              :visible.sync="imgDialogVisible"
              width="50%"
            >
              <img class="img" :src="perImg" alt="" />
              <span slot="footer" class="dialog-footer">
                <el-button @click="imgDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="imgDialogVisible = false"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="myQuillEditor"
              v-model="goodsinfo.goods_introduce"
            />
            <el-button class="btnQuill" type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeName: 0,
      goodsinfo: {
        goods_name: "",
        goods_price: null,
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      //表单校验
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
      },
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      cateList: [],
      checkList: [],
      onlyData: [],
      //图片上次的地址
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      //图片上传需要配置请求头
      tokenHeader: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      perImg: "",
      imgDialogVisible: false,
      form: {}
    };
  },
  methods: {
    async handleClick() {
      //商品动态参数
      if (this.activeName === "1") {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        console.log(res);
        if (res.meta.status != 200) return this.$message.error("数据获取失败");
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(" ");
        });
        this.checkList = res.data;
      }
      //商品静态参数
      if (this.activeName === "2") {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        console.log(res);
        if (res.meta.status != 200) return this.$message.error("数据获取失败");
        this.onlyData = res.data;
      }
      //商品图片
      if (this.activeName === "3") {
      }
    },
    //监听级联菜单
    handleChange() {
      if (this.goodsinfo.goods_cat.length !== 3)
        return (this.goodsinfo.goods_cat = []);
    },

    //获取分类商品数据
    async getCateList() {
      let { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.cateList = res.data;
    },
    //钩子函数，监听tag跳转
    beforeTagLeave(activeName, oldName) {
      if (oldName == 0 && this.goodsinfo.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    //预览图片
    handlePreview(file) {
      console.log(file);
      this.perImg = file.response.data.url;
      this.imgDialogVisible = true;
    },
    //删除图片
    handleRemove(file) {
      console.log(file);
      console.log(this.goodsinfo);
      //查找索引的方法
      let i = this.goodsinfo.pics.findIndex(
        (item) => item === file.response.data.tmp_path
      );
      console.log(i);
      this.goodsinfo.pics.splice(i, 1);
      console.log(this.goodsinfo);
    },
    //上传图片
    handSuccess(response) {
      console.log(response);
      let successPath = response.data.tmp_path;
      this.goodsinfo.pics.push(successPath);
      console.log(this.goodsinfo);
    },
    add(){
        this.$refs.addGoodsRef.validate(async vaild =>{
          //验证表单
          if(!vaild) return this.$message.error("请输入必填内容")
          //深度拷贝goods_cat，因为与级联选择器需要数组冲突
          this.form = _.cloneDeep(this.goodsinfo)
          //将form的goods_cat转为字符串
          this.form.goods_cat = this.form.goods_cat.join(",")
          //将静态参数和动态参数加入form中
          this.checkList.forEach(item =>{
            this.form.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(" ")
            })
          })
          this.onlyData.forEach(item =>{
            this.form.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            })
          })
        console.log(this.form)
        let {data:res} = await this.$http.post("goods",this.form)
        console.log(res)
        if(res.meta.status != 201) return this.$message.error("添加商品失败")
        this.$message.success("添加商品成功")
        this.$router.push('/goods')

        })
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId: function () {
      if (this.goodsinfo.goods_cat.length === 3) {
        return this.goodsinfo.goods_cat[2];
      } else {
        return [];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-form-item {
  text-align: left;
}
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin: 0;
  margin: 0 10px 0 0;
}
.el-checkbox.is-bordered.el-checkbox--small {
  margin: 0;
  margin: 0 10px 0 0;
}
.img {
  width: 100%;
}
.btnQuill{
  margin-top: 20px;
  display: flex;
}
</style>